<?php

class indexController extends baseController
{

    //首页
    public function indexAction()
    {
        echo "OK";
    }

    /**
     * 统一查询方法
     * @date: 2019年1月28日 下午2:53:06
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function searchAction()
    {
        //接口安全验证开始
        //$this->apisafefilter();

        $commonClass = $this->common;
        //处理查询表
        $t = $this->TablenameFilter($commonClass->Requert("t"));

        //处理返回的列名称，用于多表查询
        $liemingcheng = $this->LiemingchengFilter($commonClass->Requert("liemingcheng"));
        //返回条数
        $number = $this->NumberFilter($commonClass->Requert("number"));
        //当前页数
        $page = $this->NumberFilter($commonClass->Requert("page"));

        // 		   ordertype：排序字段，默认已有ID，如不需要排序请为空
        $ordertype = $commonClass->SafeFilterStr($commonClass->Requert("ordertype"));
        // 		   orderby：排序方式，升序和降序
        $orderby = $commonClass->SafeFilterStr($commonClass->Requert("orderby"));
        // 		   sqlvalue：默认查询方式,如果有多个用逗号分隔，“|”会替换成=号
        $sqlvalue = $this->SqlvalueFilter($commonClass->Requert("sqlvalue"));
        // Print 打印测试，如需把sql打印出来，把改成yes，需要显示结果可不传或为空。
        $print = $commonClass->Requert("print");

        //拼接为sql语句
        $_sql = $this->getSql($t, $liemingcheng, $number, $page, $ordertype, $orderby, $sqlvalue);
        if ($print == "yes") {
            echo $_sql;
            die();
        }

        $temp_model = new Model($t);
        $temp_arr = $temp_model->findBySql($_sql);
        //挂载控件类
        $this->library("Component");
        $ComponentClass = new Component();
        $tableModel = new tableModel();
        $filedModel = new filedModel();
        $table_id = $tableModel->gettableidBytablename($t);
        $filedAraay = $filedModel->getallFiledByTableid($table_id);

        foreach ($filedAraay as $v) {
            //处理不同字段的显示数据
            foreach ($temp_arr as $k1 => $v1) {
                $v1[$v['u1']] = $ComponentClass->showvalueKj($v['u7'], $v['u2'], $v['u1'], $v1[$v['u1']], $v['u3'], $v['id']);
                $temp_arr[$k1] = $v1;
            }
        }
        $_tableList["data"] = $temp_arr;
        $_tableList["count"] = $temp_model->total($sqlvalue);

        returnSuccess($_tableList, "成功", $code = 0);

    }

    /**
     * 添加数据统一接口
     * @date: 2019年2月14日 下午5:50:41
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function addAction()
    {
        //接口安全验证开始
        //$this->apisafefilter();

        $commonClass = $this->common;
        //处理查询表
        $t = $this->TablenameFilter($commonClass->Requert("t"));

        $tableName = str_replace("sl_", "", $t);
        //待处理的表
        $tableModel = new Model($tableName);
        $moxingModel = new tableModel();
        $model_id = $moxingModel->gettableidBytablename($tableName);
        //1.收集表单数据
        $data = $tableModel->getFieldArray();

        //单独处理留言
        if ($tableName == "liuyan") {
            //查询用户数据
            $yonghu_data = (new yonghuModule())->findOne($data["yonghu"]);
            $data["mingcheng"] = $yonghu_data["mingcheng"];
            $data["shoujihao"] = $yonghu_data["shoujihao"];
        }

        //2.验证和处理
        $this->helper('input');
        $data = deepspecialchars($data);

        //时间默认为空则为当前时间
        if (!isset($data['dtime'])) {
            $data['dtime'] = date("Y-m-d H:i:s");
        }

        if ($tableModel->insert($data)) {

            returnSuccess("更新成功", "成功", $code = 0);

        } else {

            returnFail("更新失败");
        }

    }

    /**
     * 统一修改接口
     * @date: 2019年2月21日 下午5:27:50
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function editAction()
    {
        //接口安全验证开始
        //$this->apisafefilter();

        $commonClass = $this->common;
        //处理查询表
        $t = $this->TablenameFilter($commonClass->Requert("t"));

        $tableName = str_replace("sl_", "", $t);
        //待处理的表
        $tableModel = new Model($tableName);
        $moxingModel = new tableModel();
        $model_id = $moxingModel->gettableidBytablename($tableName);
        //1.收集表单数据
        $data = $tableModel->getFieldArray();
        //2.验证和处理
        $this->helper('input');
        $data = deepspecialchars($data);

        if ($tableModel->update($data)) {

            returnSuccess("更新成功", "成功", $code = 0);
        } else {
            returnFail("更新失败");
        }

    }

    /**
     * 统一删除接口
     * @date: 2019年2月21日 下午5:27:50
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function delAction()
    {
        //接口安全验证开始
        //$this->apisafefilter();

        $commonClass = $this->common;
        //处理查询表
        $t = $this->TablenameFilter($commonClass->Requert("t"));

        $tableName = str_replace("sl_", "", $t);
        //待处理的表
        $tableModel = new Model($tableName);
        $moxingModel = new tableModel();
        $model_id = $moxingModel->gettableidBytablename($tableName);
        //1.收集表单数据
        $data = $tableModel->getFieldArray();
        //2.验证和处理
        $this->helper('input');
        $data = deepspecialchars($data);

        $detail = $tableModel->findOne($data['id']);
        if ($detail) {
            if ($detail['yonghu'] != $data['yonghu']) {
                returnFail("不能删除其他用户的数据");

            } else {
                if ($tableModel->delete($data['id'])) {

                    returnSuccess("删除成功", "成功", $code = 0);
                } else {
                    returnFail("删除失败");
                }

            }

        } else {
            returnFail("当前记录不存在");
        }


    }

    /**
     * 获取token
     * @date: 2019年1月22日 下午6:57:31
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function gettokenAction()
    {
        $appkey = $this->appkey;
        $time = time() + $this->tokentime;
        $data["appkey"] = $appkey;
        $data["time"] = $time;
        //echo serialize($data);die();
        $token = $this->common->encryptByqingmiphp(serialize($data));
        returnSuccess($token, $this->getcodestr(2001), $code = 0);

    }

    /**
     * 微信登录授权
    */
    public function getwxuserinfoAction()
    {
        $code = $this->common->Requert("code");
        $APPID = $GLOBALS['config_account']['WX_APPID'];
        $SECRET = $GLOBALS['config_account']['WX_SECRET'];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$APPID}&secret={$SECRET}&js_code={$code}&grant_type=authorization_code";
        //die($url);
        $UserInfo = json_decode($this->common->get_webHtml($url), true);
        //var_dump($UserInfo);die();
        //挂载微信小程序解密文件
        include_once LIB_PATH . "Wx/xcx/" . "wxBizDataCrypt.php"; #此文件见下方
        $sessionKey = $UserInfo['session_key'];
        #上图getuserinfo接口里返回的数据
        $encryptedData = $this->common->Requert("encryptedData");
        $iv = $this->common->Requert("iv");
        $pc = new WXBizDataCrypt($APPID, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {
            //更新用户数据
            $yonghuM = new yonghuModule();
            $_data = $yonghuM->insertOrupdateYonghuByWxInfo(json_decode($data, true));
            //查询订阅栏目
            $dingyuelanmuM = new dingyuejiluModule();
            if (count($dingyuelanmuM->getdingyuelistByYonghu($_data["id"])) > 0) {
                $_data["dingyueStatus"] = true;
            } else {
                $_data["dingyueStatus"] = false;
            }
            returnSuccess($_data, "登录成功", $code = 0);
        } else {
            returnFail($errCode);
        }
    }

    /**
     * 发送短信
     * @date: 2019年2月21日 下午3:05:35
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function sendsmsAction()
    {
        //接口安全验证开始
        $this->apisafefilter();

        $shoujihao = $this->common->Requert("shoujihao");
        $this->library("Sms");
        $smsClass = new Sms();

        //验证用户是否可以登录
        $daoruyonghuM = new daoruyonghuModule();
        if ($daoruyonghuM->ableLogin()) {

            $smsClass->lingkai($shoujihao, "", "验证码");
            returnSuccess("短信已发送", "成功", $code = 0);


        } else {
            returnSuccess("该手机号没有登录权限", "成功", 1);
        }


    }

    /**
     * 验证验证码
     * @date: 2019年2月21日 下午4:28:56
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function checksmsAction()
    {
        //接口安全验证开始
        //$this->apisafefilter();
        $shoujihao = $this->common->Requert("shoujihao");
        $yzm = $this->common->Requert("yzm");
        $yonghu = $this->common->Requert("yonghu");

        $this->library("Sms");
        $smsClass = new Sms();
        $_data = $smsClass->checkyzm($shoujihao, $yzm);
        if ($_data['status']) {
            $yonghuM = new yonghuModule();
            $yonghuM->update(['id' => $yonghu, 'shoujihao' => $shoujihao]);
            $usreInfo = $yonghuM->getdetailByid($yonghu);
            //查询订阅栏目
            $dingyuelanmuM = new dingyuejiluModule();
            if (count($dingyuelanmuM->getdingyuelistByYonghu($yonghu)) > 0) {
                $usreInfo["dingyueStatus"] = true;
            } else {
                $usreInfo["dingyueStatus"] = false;
            }

            returnSuccess($usreInfo, "成功", $code = 0);
        } else {
            returnFail($_data['msg']);
        }

    }

    /**
     * 发送微信模板消息短信
     * @date: 2019年2月21日 下午3:05:35
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function sendwxsmsAction()
    {
// 	    //接口安全验证开始
        //$this->apisafefilter();

        $APPID = $GLOBALS['config_account']['WX_APPID'];
        $SECRET = $GLOBALS['config_account']['WX_SECRET'];

        include_once LIB_PATH . "Wx/xcx/" . "wxTemplateSms.php"; #此文件见下方

        $WxTmplateSmsClass = new wxTemplateSms($APPID, $SECRET);

        $openid = "oL15O5cpiXXcC0SDSOB3sbhErMUI";
        $template_id = "AveEe47atNGL50YC_3p8z6Zk_0Nu1skclceFs1EXPAI";
        $formid = "045f975f13e84bc694a8ad3880672df5";

        $post_data = array(
            // 用户的 openID，可用过 wx.getUserInfo 获取
            "touser" => $openid,
            // 小程序后台申请到的模板编号
            "template_id" => $template_id,
            // 点击模板消息后跳转到的页面，可以传递参数
            "page" => "/pages/index/index",
            // 第一步里获取到的 formID
            "form_id" => $formid,
            // 数据
            "data" =>
                [
                    "keyword1" =>
                        [
                            "value" => '123',

                        ],
                    "keyword2" =>
                        [
                            "value" => '321',

                        ],
                    "keyword3" =>
                        [
                            "value" => '123321',

                        ],

                ]


        );


        $WxTmplateSmsClass->sendSms($post_data);


    }

    /**
     * 定时任务
     * @date: 2019年2月21日 下午3:05:35
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function dingshiAction()
    {
        ini_set('display_errors', 1);            //错误信息
        ini_set('display_startup_errors', 1);    //php启动错误信息
        error_reporting(-1);                                   //打印出所有的 错误信息

        set_time_limit(0);

        $APPID = $GLOBALS['config_account']['WX_APPID'];
        $SECRET = $GLOBALS['config_account']['WX_SECRET'];
        include_once LIB_PATH . "Wx/xcx/" . "wxTemplateSms.php"; #此文件见下方
        $WxTmplateSmsClass = new wxTemplateSms($APPID, $SECRET);
        $guanjiancitongjiM = new guanjiancitongjiModule();
        $parameterM = new parameterModel();

        $cur_hour = (int)date('H', time());
        if ($cur_hour >= 0 && $cur_hour <= 24) {
            $yonghuM = new yonghuModule();
            $formidM = new Model("formid");
            $zhengcekuM = new Model("zhengceku");
            $dingyuejiluM = new dingyuejiluModule();
            $rizhiM = new rizhiModule();

//            $yonghulist = $yonghuM->findBySql("SELECT id,wx_openid,(select formid from sl_formid as f where f.yonghu = y.id LIMIT 0,1) as formid ,(select id from sl_formid as f where f.yonghu = y.id LIMIT 0,1) as fid from sl_yonghu as y");

            $sql = "select y.id,y.wx_openid,f.id as fid from sl_yonghu as y join sl_formid as f on y.id = f.yonghu";
            $yonghulist = $formidM->findBySql($sql);

            //循环发送
            $shezhiModule = new shezhiModule();
            foreach ($yonghulist as $k => $v) {
                //查询该用户是否点击了订阅
                $res = $shezhiModule->getzhuangtaiByYonghu($v["id"]);
                if (!$res){ //用户取消了订阅的不推送
                    continue;
                }

                $yonghudata = $v;

                $openid = $yonghudata["wx_openid"];
                $template_id = "VlcvlUgb0s1H3PQEgZYidXC4h7mel3rn2Ah2KgVOkJQ";
//                $formid = $yonghudata["formid"];
                $keyword3_value = "";

                $_whereStr = "   chaifenzhuangtai=3 ";
                $whereStr = (new yonghuModule())->getdingyuelanmuSqlByYonghuid($yonghudata['id']);

                if ($whereStr != "") {
                    $whereStr = $_whereStr . " and ({$whereStr}) ";
                }

                //查询用户订阅的政策更新
                $zcList = $zhengcekuM->find("id,biaoqian")->where($whereStr)->orderBy("fawenriqi desc,id desc")->all();
                if (count($zcList) <= 0) {
                    continue;
                }

                //拼接订阅栏目
                foreach ($zcList as $k1 => $v1) {
                    if (strlen($keyword3_value) > 10) {
                        $keyword3_value = $keyword3_value . "...";
                        break;
                    }
                    if ($keyword3_value == "") {
                        $keyword3_value = $v1["biaoqian"];
                    } else {
                        $keyword3_value = $keyword3_value . "," . $v1["biaoqian"];
                    }
                }

                //截取长度
                if (strlen($keyword3_value) > 30){
                    $keyword3_value = mb_substr($keyword3_value,0,15,"utf-8")."...";
                }

                $post_data = array(
                    // 用户的 openID，可用过 wx.getUserInfo 获取
                    "touser" => $openid,
                    // 小程序后台申请到的模板编号
                    "template_id" => $template_id,
                    // 点击模板消息后跳转到的页面，可以传递参数
                    "page" => "/pages/index/index",
                    // 第一步里获取到的 formID
//                    "form_id" => $formid,
                    // 数据
                    "data" =>
                        [
                            "phrase1" =>
                                [
                                    "value" => "订阅的内容",
                                ],
                            "thing5" =>
                                [
                                    "value" => $keyword3_value,
                                ],
                            "thing8" =>
                                [
                                    "value" => "为您找到" . count($zcList) . "条订阅政策信息快去看看吧",
                                ],
                            "date7" =>
                                [
                                    "value" => date("Y-m-d"),
                                ],
                        ]
                );

                $re_data = $WxTmplateSmsClass->sendSms($post_data);
                //删除已发送的formid
                $formidM->delete($yonghudata["fid"]);
                //插入模版消息
                $rizhiData["dtime"] = date("Y-m-d");
                $rizhiData["yonghu"] = $yonghudata["id"];
                $rizhiData["leixing"] = 3;
                $rizhiM->insert($rizhiData);
                flush();
            }
        }

    }

    /**
     * Name:级别转换为所属地区
     * Notes:
     * User: gonghuayao
     * Date: 2020-01-13
     * Time: 17:47
     */
    public function handleSuoshudiquAction()
    {
        $zhengcekuM = new zhengcekuModule();
        $zhengceku_list = $zhengcekuM->find("id,jibie")->all();
        $parameterM = new parameterModel();
        foreach ($zhengceku_list as $k => $v) {
            $_jibie = $v["jibie"];
            if ($_jibie == "") {
                continue;
            } else {
                if ($_jibie > 4) {
                    $parameter_data = $parameterM->where("classid='373' and u2='{$_jibie}' ")->one();
                    if (count($parameter_data) > 0) {
                        $v["suoshudiqu"] = "国家-四川省-成都市-" . $parameter_data["u1"];
                    }
                } else if ($_jibie == 3) {
                    $v["suoshudiqu"] = "国家-四川省-成都市";
                } else if ($_jibie == 2) {
                    $v["suoshudiqu"] = "国家-四川省";
                } else if ($_jibie == 1) {
                    $v["suoshudiqu"] = "国家";
                }
                //更新数据库
                $zhengcekuM->update($v);
            }

        }

    }

    /**
     * 查询banner
     * @date: 2020-11-18 17:26:19
     * @author: junshi
     */
    public function getBannerAction()
    {
        $banner = (new bannerModule())->orderBy("quanzhong desc,id desc")->all();
        returnSuccess($banner);
    }

}
